package org.kabanyo.utils {

	/**
	 * Make some statistic calculation to defined dataseries.
	 *
	 * @author Desky Natalio
	 *
	 */
	public class DataSeriesUtil {
		public function DataSeriesUtil() {
			//NOOP
		}

		public static function sum(data:Array, field:String):Number {
			var result:Number = 0.0;
			for (var i:int = 0; i < data.length; i++) {
				if (data[i][field] is Number) {
					result += data[i][field];
				}
			}
			return result;
		}

		public static function count(data:Array, field:String):int {
			var result:int = 0;
			for (var i:int = 0; i < data.length; i++) {
				if (data[i][field]) {
					result++;
				}
			}

			return result;
		}

		public static function avg(data:Array, field:String):Number {
			return sum(data, field) / data.length;
		}

		public static function max(data:Array, field:String):Number {
			var result:Number;
			for (var i:int = 0; i < data.length; i++) {
				if (!result || result < data[i][field]) {
					result = data[i][field];
				}
			}
			return result;
		}

		public static function min(data:Array, field:String):Number {
			var result:Number;
			for (var i:int = 0; i < data.length; i++) {
				if (!result || result > data[i][field]) {
					result = data[i][field];
				}
			}
			return result;
		}

		public static function distinct(data:Array, field:String):Array {
			var results:Array = [];
			for (var i:int = 0; i < data.length; i++) {
				var existed:Boolean = false;
				for (var j:int = 0; j < results.length; j++) {
					existed = (data[i][field] == results[i]);
					if (existed) {
						break;
					}
				}
				if (existed) {
					results.push(data[i][field]);
				}
			}
			return results;
		}
	}
}
